<template>
  <div class="p-2">
    <!-- 网关管理模块 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="网关名称" prop="gatewayName">
          <el-input
            v-model="queryParams.gatewayName"
            placeholder="请输入网关名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="网关状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="网关状态" clearable style="width: 150px">
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="故障" value="error" />
          </el-select>
        </el-form-item>
        <el-form-item label="网关类型" prop="gatewayType">
          <el-select v-model="queryParams.gatewayType" placeholder="网关类型" clearable style="width: 150px">
            <el-option label="边缘网关" value="edge" />
            <el-option label="协议网关" value="protocol" />
            <el-option label="云端网关" value="cloud" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域" prop="region">
          <el-select v-model="queryParams.region" placeholder="所属区域" clearable style="width: 150px">
            <el-option label="华东区" value="east" />
            <el-option label="华南区" value="south" />
            <el-option label="华北区" value="north" />
            <el-option label="西南区" value="southwest" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="10" style="margin-bottom: 8px">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.totalGateways }}</div>
            <div class="stat-label">总网关数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value online">{{ statistics.onlineGateways }}</div>
            <div class="stat-label">在线网关</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value connected">{{ statistics.connectedDevices }}</div>
            <div class="stat-label">连接设备</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value error">{{ statistics.errorGateways }}</div>
            <div class="stat-label">故障网关</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增网关</el-button>
          <el-button type="success" plain icon="Upload" @click="handleImport">批量导入</el-button>
          <el-button type="warning" plain icon="Download" @click="handleExport">导出数据</el-button>
          <el-button type="danger" plain icon="Delete" @click="handleBatchDelete" :disabled="!multipleSelection.length">批量删除</el-button>
        </div>
        <div class="toolbar-right">
          <el-button type="info" plain icon="Refresh" @click="handleRefresh">刷新</el-button>
          <el-button type="primary" plain icon="Monitor" @click="handleMonitor">监控面板</el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="loading"
        :data="gatewayList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="网关ID" prop="gatewayId" width="120" align="center" />
        <el-table-column label="网关名称" prop="gatewayName" width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" @click="handleView(scope.row)">{{ scope.row.gatewayName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="网关类型" prop="gatewayType" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getGatewayTypeTagType(scope.row.gatewayType)">{{ getGatewayTypeText(scope.row.gatewayType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="IP地址" prop="ipAddress" width="140" align="center" />
        <el-table-column label="端口" prop="port" width="80" align="center" />
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="连接设备" prop="deviceCount" width="100" align="center">
          <template #default="scope">
            <el-link type="primary" @click="handleViewDevices(scope.row)">{{ scope.row.deviceCount }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="CPU使用率" prop="cpuUsage" width="120" align="center">
          <template #default="scope">
            <el-progress :percentage="scope.row.cpuUsage" :color="getProgressColor(scope.row.cpuUsage)" />
          </template>
        </el-table-column>
        <el-table-column label="内存使用率" prop="memoryUsage" width="120" align="center">
          <template #default="scope">
            <el-progress :percentage="scope.row.memoryUsage" :color="getProgressColor(scope.row.memoryUsage)" />
          </template>
        </el-table-column>
        <el-table-column label="所属区域" prop="region" width="100" align="center" />
        <el-table-column label="最后上线" prop="lastOnlineTime" width="160" align="center" />
        <el-table-column label="操作" width="240" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" plain size="small" icon="View" @click="handleView(scope.row)">详情</el-button>
            <el-button type="success" plain size="small" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="warning" plain size="small" icon="Setting" @click="handleConfig(scope.row)">配置</el-button>
            <el-button type="danger" plain size="small" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑网关对话框 -->
    <GatewayFormDialog
      v-model:visible="dialog.visible"
      :form-data="form"
      @save="handleSaveGateway"
      @cancel="dialog.visible = false"
    />

    <!-- 网关详情对话框 -->
    <GatewayDetailDialog
      v-model:visible="detailDialog.visible"
      :detail-data="detailData"
    />

    <!-- 网关配置对话框 -->
    <GatewayConfigDialog
      v-model:visible="configDialog.visible"
      :config-data="configForm"
      @save="handleSaveConfig"
      @cancel="configDialog.visible = false"
    />

    <!-- 连接设备对话框 -->
    <ConnectedDevicesDialog
      v-model:visible="deviceDialog.visible"
      :gateway-id="currentGatewayId"
      @view-device="handleViewDevice"
      @disconnect="handleDisconnectDevice"
    />
  </div>
</template>

<script setup name="GatewayManage" lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Upload, Download, Delete, View, Edit, Setting, Monitor, CopyDocument } from '@element-plus/icons-vue'
import GatewayFormDialog from './components/GatewayFormDialog.vue'
import GatewayDetailDialog from './components/GatewayDetailDialog.vue'
import GatewayConfigDialog from './components/GatewayConfigDialog.vue'
import ConnectedDevicesDialog from './components/ConnectedDevicesDialog.vue'

// 响应式数据
const loading = ref(false)
const total = ref(0)
const multipleSelection = ref([])


// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  gatewayName: '',
  status: '',
  gatewayType: '',
  region: ''
})

// 统计数据
const statistics = reactive({
  totalGateways: 45,
  onlineGateways: 38,
  connectedDevices: 1256,
  errorGateways: 2
})

// 网关列表
const gatewayList = ref([
  {
    gatewayId: 'GW001',
    gatewayName: '华东区边缘网关01',
    gatewayType: 'edge',
    ipAddress: '192.168.1.100',
    port: 8080,
    status: 'online',
    deviceCount: 156,
    cpuUsage: 45,
    memoryUsage: 62,
    diskUsage: 38,
    region: '华东区',
    firmwareVersion: 'v2.1.3',
    lastOnlineTime: '2024-01-15 14:30:25',
    createTime: '2024-01-10 09:15:30',
    uptime: '5天12小时',
    description: '负责华东区域设备接入管理'
  },
  {
    gatewayId: 'GW002',
    gatewayName: '华南区协议网关01',
    gatewayType: 'protocol',
    ipAddress: '192.168.2.100',
    port: 8081,
    status: 'online',
    deviceCount: 89,
    cpuUsage: 32,
    memoryUsage: 48,
    diskUsage: 55,
    region: '华南区',
    firmwareVersion: 'v2.0.8',
    lastOnlineTime: '2024-01-15 14:28:15',
    createTime: '2024-01-08 16:20:45',
    uptime: '7天8小时',
    description: '负责协议转换和数据处理'
  },
  {
    gatewayId: 'GW003',
    gatewayName: '云端网关主节点',
    gatewayType: 'cloud',
    ipAddress: '10.0.1.50',
    port: 443,
    status: 'offline',
    deviceCount: 0,
    cpuUsage: 0,
    memoryUsage: 0,
    diskUsage: 0,
    region: '华北区',
    firmwareVersion: 'v2.2.1',
    lastOnlineTime: '2024-01-14 18:45:30',
    createTime: '2024-01-05 14:35:20',
    uptime: '0天0小时',
    description: '云端数据汇聚和分析'
  },
  {
    gatewayId: 'GW004',
    gatewayName: '西南区边缘网关02',
    gatewayType: 'edge',
    ipAddress: '192.168.3.100',
    port: 8082,
    status: 'error',
    deviceCount: 45,
    cpuUsage: 85,
    memoryUsage: 92,
    diskUsage: 78,
    region: '西南区',
    firmwareVersion: 'v2.1.1',
    lastOnlineTime: '2024-01-15 12:15:40',
    createTime: '2024-01-12 10:45:15',
    uptime: '3天2小时',
    description: '西南区域设备管理网关'
  },
  {
    gatewayId: 'GW005',
    gatewayName: '华东区协议网关02',
    gatewayType: 'protocol',
    ipAddress: '192.168.1.101',
    port: 8083,
    status: 'online',
    deviceCount: 234,
    cpuUsage: 58,
    memoryUsage: 71,
    diskUsage: 42,
    region: '华东区',
    firmwareVersion: 'v2.1.5',
    lastOnlineTime: '2024-01-15 14:32:10',
    createTime: '2024-01-09 08:30:45',
    uptime: '6天6小时',
    description: '协议转换专用网关'
  }
])



// 对话框状态
const dialog = reactive({
  visible: false,
  title: ''
})

const detailDialog = reactive({
  visible: false
})

const configDialog = reactive({
  visible: false
})

const deviceDialog = reactive({
  visible: false
})

// 当前网关ID（用于连接设备对话框）
const currentGatewayId = ref('')

// 表单数据
const form = reactive({
  gatewayId: '',
  gatewayName: '',
  gatewayType: '',
  ipAddress: '',
  port: 8080,
  region: '',
  status: 'online',
  description: ''
})

// 配置表单
const configForm = reactive({
  heartbeatInterval: 60,
  reportInterval: 300,
  connectionTimeout: 30,
  retryCount: 3,
  protocol: 'mqtt',
  dataFormat: 'json',
  encryption: 'tls',
  logLevel: 'info',
  logRetentionDays: 30,
  logFileSize: 100
})

// 详情数据
const detailData = reactive({})

// 表单验证规则
const rules = {
  gatewayName: [{ required: true, message: '请输入网关名称', trigger: 'blur' }],
  gatewayType: [{ required: true, message: '请选择网关类型', trigger: 'change' }],
  ipAddress: [{ required: true, message: '请输入IP地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口', trigger: 'blur' }],
  region: [{ required: true, message: '请选择所属区域', trigger: 'change' }]
}

// 获取网关类型标签类型
const getGatewayTypeTagType = (type: string) => {
  const typeMap = {
    edge: 'primary',
    protocol: 'success',
    cloud: 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取网关类型文本
const getGatewayTypeText = (type: string) => {
  const typeMap = {
    edge: '边缘网关',
    protocol: '协议网关',
    cloud: '云端网关'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap = {
    online: 'success',
    offline: 'info',
    error: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    online: '在线',
    offline: '离线',
    error: '故障'
  }
  return statusMap[status] || status
}

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 50) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

// 查询
const handleQuery = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
  }, 1000)
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    gatewayName: '',
    status: '',
    gatewayType: '',
    region: ''
  })
  handleQuery()
}

// 新增
const handleAdd = () => {
  dialog.title = '新增网关'
  dialog.visible = true
  Object.assign(form, {
    gatewayId: '',
    gatewayName: '',
    gatewayType: '',
    ipAddress: '',
    port: 8080,
    region: '',
    status: 'online',
    description: ''
  })
}

// 编辑
const handleEdit = (row: any) => {
  dialog.title = '编辑网关'
  dialog.visible = true
  Object.assign(form, row)
}

// 查看详情
const handleView = (row: any) => {
  Object.assign(detailData, row)
  detailDialog.visible = true
}

// 配置
const handleConfig = (row: any) => {
  configDialog.visible = true
}

// 查看连接设备
const handleViewDevices = (row: any) => {
  currentGatewayId.value = row.gatewayId
  deviceDialog.visible = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除网关"${row.gatewayName}"？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    handleQuery()
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm('确认删除选中的网关？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量删除成功')
    handleQuery()
  })
}

// 导入
const handleImport = () => {
  ElMessage.info('导入功能开发中')
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 刷新
const handleRefresh = () => {
  handleQuery()
}

// 监控面板
const handleMonitor = () => {
  ElMessage.info('监控面板功能开发中')
}

// 保存配置
const handleSaveConfig = () => {
  ElMessage.success('配置保存成功')
  configDialog.visible = false
}

// 保存网关（新增/编辑）
const handleSaveGateway = (formData: any) => {
  // 模拟保存逻辑
  ElMessage.success(formData.gatewayId ? '编辑成功' : '新增成功')
  dialog.visible = false
  handleQuery()
}

// 查看设备详情
const handleViewDevice = (device: any) => {
  ElMessage.info(`查看设备详情: ${device.deviceName}`)
}

// 断开设备连接
const handleDisconnectDevice = (device: any) => {
  ElMessage.success(`设备 ${device.deviceName} 连接已断开`)
}

// 选择变更
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

// 分页大小变更
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  handleQuery()
}

// 当前页变更
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page
  handleQuery()
}

// 组件挂载
onMounted(() => {
  handleQuery()
})
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  gap: 10px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-value.online {
  color: #67c23a;
}

.stat-value.connected {
  color: #409eff;
}

.stat-value.error {
  color: #f56c6c;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.system-info {
  text-align: center;
  padding: 20px;
}

.info-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}
</style>